package com.iotp.utils.zb;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.Consts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * 请求方法
 */
public class RequestUtil {
    private static Logger logger = LoggerFactory.getLogger(RequestUtil.class);


    public static JSONObject sendPost(String url, JSONObject jsonObject){
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String appKey = "c81aee426f3baeb55af46a18ebec8892";
            String appSecret = "753413b29263";
            String nonce = System.currentTimeMillis()+"";
            String curTime = String.valueOf((new Date()).getTime() / 1000L);
            String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce ,curTime);//参考 计算CheckSum的java代码

            // 设置请求的header
            httpPost.addHeader("AppKey", appKey);
            httpPost.addHeader("Nonce", nonce);
            httpPost.addHeader("CurTime", curTime);
            httpPost.addHeader("CheckSum", checkSum);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");

            // 设置请求的参数
            StringEntity params = new StringEntity(JSONObject.toJSONString(jsonObject),Consts.UTF_8);
            httpPost.setEntity(params);

            // 执行请求
            HttpResponse response = httpClient.execute(httpPost);

            // 打印执行结果
            String res = EntityUtils.toString(response.getEntity(), "utf-8");
            return JSONObject.parseObject(res);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("请求异常", e);
            return null;
        }
    }
}
